package com.wait.onlinepicture.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wait.onlinepicture.annotation.AuthCheck;
import com.wait.onlinepicture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.wait.onlinepicture.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.wait.onlinepicture.api.aliyunai.sub.AliYunAiApi;
import com.wait.onlinepicture.api.imagesearch.ImageSearchApiFacade;
import com.wait.onlinepicture.api.imagesearch.model.ImageSearchResult;
import com.wait.onlinepicture.common.BaseResponse;
import com.wait.onlinepicture.common.DeleteRequest;
import com.wait.onlinepicture.common.ResultUtils;
import com.wait.onlinepicture.constant.UserConstant;
import com.wait.onlinepicture.exception.BusinessException;
import com.wait.onlinepicture.exception.ErrorCode;
import com.wait.onlinepicture.exception.ThrowUtils;
import com.wait.onlinepicture.manager.auth.SpaceUserAuthManager;
import com.wait.onlinepicture.manager.auth.StpKit;
import com.wait.onlinepicture.manager.auth.annotation.SaSpaceCheckPermission;
import com.wait.onlinepicture.manager.auth.model.SpaceUserPermissionConstant;
import com.wait.onlinepicture.model.dto.picture.*;
import com.wait.onlinepicture.model.entity.Picture;
import com.wait.onlinepicture.model.entity.Space;
import com.wait.onlinepicture.model.entity.User;
import com.wait.onlinepicture.model.vo.picture.PictureTagCategory;
import com.wait.onlinepicture.model.vo.picture.PictureVO;
import com.wait.onlinepicture.service.PictureService;
import com.wait.onlinepicture.service.SpaceService;
import com.wait.onlinepicture.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author with葡萄成熟时
 * @version 1.0
 * 图片相关接口
 */

@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private PictureService pictureService;
    @Resource
    private UserService userService;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;
    @Resource
    private SpaceService spaceService;
    /**
     * description 上传图片（可重新上传）
     * author Wait葡萄成熟时
     * date 上午10:00 2025/3/18
     */
    @ApiOperation("上传图片（可重新上传）")
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    /*@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)*/
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * description 通过 URL 上传图片（可重新上传）
     * author Wait葡萄成熟时
     * date 下午11:09 2025/3/26
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }


    /**
     * description 删除图片
     * author Wait葡萄成熟时
     * date 上午12:14 2025/3/19
     */
    @ApiOperation("删除图片")
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(), loginUser);

        return ResultUtils.success(true);
    }


    /**
     * description 更新图片（仅管理员可用）
     * author Wait葡萄成熟时
     * date 上午12:14 2025/3/19
     */
    @ApiOperation("更新图片（仅管理员可用）")
    @PostMapping("/update")

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        // 补充审核参数
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * description 根据 id 获取图片（仅管理员可用）
     * author Wait葡萄成熟时
     * date 上午12:14 2025/3/19
     */
    @ApiOperation("根据 id 获取图片（仅管理员可用）")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }


    /**
     * description 根据 id 获取图片（封装类）
     * author Wait葡萄成熟时
     * date 上午12:14 2025/3/19
     */
    @ApiOperation("根据 id 获取图片（封装类）")
    @GetMapping("/get/vo")

    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        Space space = null;
        if (spaceId != null) {
            // 编程式校验权限
            boolean b = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!b, ErrorCode.NO_AUTH_ERROR);


            //已经改为注解鉴权
            //pictureService.checkPictureAuth(loginUser, picture);


            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space==null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");


        }
        // 获取权限列表
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }


    /**
     * description 分页获取图片列表（仅管理员可用）
     * author Wait葡萄成熟时
     * date 上午12:14 2025/3/19
     */
    @ApiOperation("分页获取图片列表（仅管理员可用）")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }


    /**
     * description 分页获取图片列表（封装类）
     * author Wait葡萄成熟时
     * date 上午12:14 2025/3/19
     */
    @ApiOperation("分页获取图片列表（封装类）带缓存")
    @PostMapping("/list/page/vo")

    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        return ResultUtils.success(pictureService.listPictureVOByPage(pictureQueryRequest, request));
    }


    /**
     * description 编辑图片（给用户使用）
     * author Wait葡萄成熟时
     * date 上午12:14 2025/3/19
     */
    @ApiOperation("编辑图片（给用户使用）")
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        pictureService.editPicture(pictureEditRequest, userService.getLoginUser(request));
        return ResultUtils.success(true);
    }

    /**
     * description 前端展示的标签和分类
     * author Wait葡萄成熟时
     * date 上午12:44 2025/3/19
     */
    @ApiOperation("前端展示的标签和分类")
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * description 管理员审核接口
     * author Wait葡萄成熟时
     * date 下午4:34 2025/3/26
     */
    @ApiOperation("管理员审核接口")
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * description 批量抓取图片（浏览器bing抓）
     * author Wait葡萄成熟时
     * date 上午9:36 2025/3/28
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }
/**
 * description 以图搜图
 * author Wait葡萄成熟时
 */

    @ApiOperation("以图搜图接口")
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        // 判断请求参数是否为空
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取请求参数中的图片ID
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        // 判断图片ID是否为空或小于等于0
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        // 根据图片ID获取图片信息
        Picture oldPicture = pictureService.getById(pictureId);
        // 判断图片信息是否存在
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 根据图片缩略图URL进行以图搜图
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getThumbnailUrl());
        // 返回搜索结果
        return ResultUtils.success(resultList);
    }

    /**
     * description 根据颜色搜索图片
     * author Wait葡萄成熟时
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    // 根据颜色搜索图片
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        // 判断请求参数是否为空
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取请求参数中的图片颜色
        String picColor = searchPictureByColorRequest.getPicColor();
        // 获取请求参数中的空间ID
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        // 获取登录用户
        User loginUser = userService.getLoginUser(request);
        // 根据颜色和空间ID搜索图片
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        // 返回搜索结果
        return ResultUtils.success(result);
    }

    /**
     * description 批量修改图片
     * author Wait葡萄成熟时
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * description 创建 AI 扩图任务
     * author Wait葡萄成熟时
     */

    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * description 查询 AI 扩图任务
     * author Wait葡萄成熟时
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }

}
